<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\RoomTrack\Action\Sidebar;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\SidebarAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\RoomTrack\Contract\RoomTrackContract;

/**
 * 群动态.
 *
 * Class Index
 * @Controller
 */
class Index extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * 互动轨迹表.
     * @Inject
     * @var RoomTrackContract
     */
    private $track;

    /**
     * @Middlewares({
     *     @Middleware(SidebarAuthMiddleware::class)
     * })
     * @RequestMapping(path="/sidebar/roomTrack/index", methods="GET")
     */
    public function handle()
    {
        // 接收参数
        $params['roomId'] = (int) $this->request->input('roomId');
        $params['event'] = (int) $this->request->input('event', 0);
        $page = $this->request->input('page', 1);
        $perPage = $this->request->input('perPage', 10);
        // 校验参数
        $this->validated($params);
        $where['room_id'] = $params['roomId'];
        if ($params['event'] > 0) {
            $where['event'] = $params['event'];
        }
        $options = [
            'page' => $page,
            'perPage' => $perPage,
            'orderByRaw' => 'id desc',
        ];
        $columns = [
            'id',
            'event',
            'content',
            'relation_id',
            'created_at',
        ];
        $res = $this->track->getRoomTrackList($where, $columns, $options);
        // 组织响应数据
        $data = [
            'page' => [
                'perPage' => $perPage,
                'total' => 0,
                'totalPage' => 0,
            ],
            'list' => [],
        ];
        if (empty($res['data'])) {
            return $data;
        }
        // 处理分页数据
        $data['page']['total'] = $res['total'];
        $data['page']['totalPage'] = $res['last_page'];
        // 数据处理
        $list = [];
        foreach ($res['data'] as $k => $v) {
            $day = substr($v['createdAt'], 0, 10);
            $list[$day]['week'] = $this->getWeek($day);
            $list[$day]['day'] = $day;
            try {
                if (strpos($v['content'], '{') === 0) {
                    $v['content'] = Json::decode($v['content']);
                } else {
                    $v['content'] = [
                        'title' => '',
                        'content' => $v['content'],
                    ];
                }
            } catch (\Throwable $e) {
                continue;
            }
            $v['createdAt'] = date('H:i', strtotime($v['createdAt']));
            $list[$day]['track'][] = $v;
        }
        $data['list'] = array_values($list);
        return $data;
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'roomId' => 'required|integer|min:1|bail',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'roomId.required' => '客户群id 必传',
        ];
    }

    protected function getWeek($date)
    {
        // 强制转换日期格式
        $date_str = date('Y-m-d', strtotime($date));

        // 封装成数组
        $arr = explode('-', $date_str);

        // 参数赋值
        // 年
        $year = $arr[0];

        // 月，输出2位整型，不够2位右对齐
        $month = sprintf('%02d', $arr[1]);

        // 日，输出2位整型，不够2位右对齐
        $day = sprintf('%02d', $arr[2]);

        // 时分秒默认赋值为0；
        $hour = $minute = $second = 0;

        // 转换成时间戳
        $strap = mktime($hour, $minute, $second, (int) $month, (int) $day, (int) $year);

        // 获取数字型星期几
        $number_wk = date('w', $strap);

        // 自定义星期数组
        $weekArr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];

        // 获取数字对应的星期
        return $weekArr[$number_wk];
    }
}
